 # ------------------------------------------------------------------------------
# Create 31-365d mace/death outcome plots for tested v untested
# Author: Cassidy Shubatt <cshubatt@gmail.com>
# To run: bash 03_plot_longterm_adverse.sh
# ------------------------------------------------------------------------------

# Libraries --------------------------------------------------------------------
library(here)
library(yaml)
library(data.table)
library(tidyverse)
library(glue)
library(ggplot2)

u <- modules::use(here("lib", "util.R"))
a <- modules::use(here("lib", "aesthetics.R"))
a$get_font("Optima", here::here("lib", "optima.ttf"))
temp <- here(
  "code", "03_score_diagnostics", "temp",
  "03_plot_longterm_adverse"
)
if (!dir.exists(temp)) {
  dir.create(temp)
}
overnight_lab <- ""

# Helper Functions -------------------------------------------------------------
add_labels <- function(outcome, x_var, group_var, gg, ...) {
  xlabel <- case_when(
    grepl(x_var, "stent_or_cabg") & grepl(x_var, "tested") ~ "Percentile of Predicted Risk",
    TRUE ~ x_var
  )
  ylabel <- case_when(
    grepl("macetrop_or_death", outcome) ~ "Adverse Event Rate",
    grepl("macetrop", outcome) ~ "Diagnosed Event Rate",
    grepl("death", outcome) ~ "Death Rate",
    TRUE ~ outcome
  )
  legend_label <- case_when(
    group_var == "test_010_day" ~ "Testing Group",
    TRUE ~ group_var
  )

  gg <- gg +
    labs(
      x = xlabel, y = ylabel, color = legend_label, fill = legend_label
    )
  return(gg)
}

get_filename <- function(outcome, x_var, group_var, ...) {
  x_var_lab <- case_when(
    grepl("tile_stent_or_cabg", x_var) ~ parse_number(x_var) %>%
      str_pad(3, pad = "0") %>%
      {
        glue("tile_{.}")
      },
    TRUE ~ x_var
  )
  fn <- file.path(temp, glue("{outcome}__by__{x_var_lab}__for__{group_var}.png"))
  return(fn)
}

# Load Data --------------------------------------------------------------------
message("Loading data...")
paths <- read_yaml(here("lib", "filepaths.yml"))
longterm_outcomes <- readRDS(paths$analysis$longterm_outcomes)
cohort <- readRDS(glue(paths$analysis$test_cohort)) %>%
  filter(!exclude) %>%
  u$safe_left_join(longterm_outcomes) %>%
  mutate(
    test_010_day = factor(test_010_day, labels = c("Untested", "Tested"))
  )

# Outcome Config ---------------------------------------------------------------
message("Preparing config table...")
config <- crossing(
  outcome = c(
    "macetrop_or_death_31_to_365", "death_365_day", "macetrop_31_to_365_pos",
    "death_31_to_365"
  ),
  x_var = c("tile_stent_or_cabg_004_tested"),
  group_var = c("test_010_day")
)

# Plot means -------------------------------------------------------------------
message("Plotting means...")
palette <- a$disc_palette[1:2] %>% rev()
plots <- config %>%
  mutate(
    mean_outcomes = pmap(
      ., u$get_grouped_mean_outcomes,
      population = "all", df = cohort
    )
  ) %>%
  mutate(gg = pmap(., a$tile_plot, palette = palette)) %>%
  mutate(plot = pmap(., add_labels)) %>%
  mutate(filename = pmap(., get_filename))

# Save -------------------------------------------------------------------------
message("Saving longterm outcome plots...")
saved <- plots %>%
  select(plot, filename) %>%
  pmap(ggsave, width = 10, height = 7, unit = "in")

message("Done.")
